<template>
  <div>
    <el-form :inline="true" style="overflow: auto">
      <el-form-item>
        <el-select
          style="width: 150px"
          placeholder="请选择老师"
          v-model="selectedTeacher"
          @change="onTeacherChange"
          clearable
        >
          <el-option
            :label="teacher.label"
            v-for="teacher in teacherList"
            :key="teacher.value"
            :value="teacher.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          style="width: 180px"
          placeholder="请选择项目名称"
          v-model="projectId"
          @change="tabSelect(projectId)"
        >
          <el-option
            :label="item.title"
            v-for="(item, index) in projectDataArr"
            :key="index"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          style="width: 180px"
          placeholder="请选择类别"
          v-model="categoryName"
          @change="tabSelect(categoryName)"
        >
          <el-option
            :label="item"
            v-for="(item, index) in categoryNameData"
            :key="index"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          style="width: 180px"
          placeholder="请选择子任务名称"
          v-model="subtaskSelect"
          @change="tabSelect()"
        >
          <el-option
            :label="item"
            v-for="(item, index) in subtask"
            :key="index"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item style="width: 150px">
        <el-input placeholder="请输入分数" v-model="RatingValue"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native="Inquire()">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
      border
      style="width: 100%"
      :data="tableData.slice((current - 1) * size, current * size)"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <!-- prop="date" -->
      <el-table-column label="项目名称"  prop="title">
      </el-table-column>
      <el-table-column label="类别" prop="category">
      </el-table-column>
      <el-table-column label="子任务" prop="taskName">
      </el-table-column>
      <el-table-column label="开始时间" sortable prop="startTime">
      </el-table-column>
      <el-table-column label="结束时间" sortable prop="endTime">
      </el-table-column>
      <el-table-column label="用户名"  prop="nickName">
      </el-table-column>
      <el-table-column label="用户工号" prop="userName">
      </el-table-column>
      <el-table-column
        label="子任务分数"
        width="100"
        prop="score"
      ></el-table-column>
      <el-table-column fixed="right" label="操作" width="199">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="viewPDF(scope.row)"
            >查看</el-button
          >
          <el-button
            type="primary"
            size="small"
            @click="DownloadWord(scope.row)"
            >下载Word</el-button
          >
        </template>
      </el-table-column>
    </el-table>
     <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[5, 10, 20]"
      :current-page.sync="current"
      :page-size="size"
      layout="sizes, prev, pager, slot"
      :total="tableData.length"
      row-key
    >
            <el-button type="text" @click="showMore">下一页</el-button>    
    </el-pagination>

    <!-- PDF查看弹窗 -->
    <el-dialog
      title="PDF文档查看"
      :visible.sync="pdfDialogVisible"
      width="80%"
      :before-close="handlePDFDialogClose"
    >
      <div class="pdf-viewer-container">
        <div v-if="pdfError" class="pdf-error">
          <i class="el-icon-warning"></i>
          <span>{{ pdfError }}</span>
        </div>
        <div v-else class="pdf-content">
          <!-- 使用 iframe 显示PDF（显示第一个PDF） -->
          <iframe
            v-if="pdfUrl && pdfUrl.length > 0"
            :src="pdfUrl[0]"
            width="100%"
            height="600px"
            frameborder="0"
          ></iframe>
          <div v-else class="pdf-empty">
            <p>暂无PDF文件</p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pdfDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "subexamineupdate",
  data() {
    return {
      projectName: "",
      subtaskSelect: "",
      categoryName: "",
      arr: [],
      // newArr: [],
      categoryData: [],
      projectId: "",
      size: 5,
      current: 1,
      score: "",
      dialogVisible: false,
      newScore: [],
      listScore: "",
      row: [],
      obj: {
        projectId: "",
        taskId: "",
        userId: "",
        score: "",
      },
      showData: 0,
      multipleSelection: [],
      projectDataArr: [],
      categoryNameData: [],
      taskId: "",
      subtask: [],
      tableData: [],
      RatingValue: null,
      // 老师筛选相关
      selectedTeacher: "",
      teacherList: [
        { value: "", label: "" },
       
      ],
      // PDF查看相关
      pdfDialogVisible: false,
      pdfUrl: [],
      pdfLoading: false,
      pdfError: "",
      currentPDFData: null,
    };
  },
  created() {
    this.AllData();
    this.getProjectName();
  },
  methods: {
    getProjectName() {
      this.$get("/api/projects").then((res) => {
        this.projectDataArr = res.data;
        
      });
    },
    
    // 老师选择变化处理
    onTeacherChange() {
      // 当老师选择变化时，重新查询数据
      this.Inquire();
    },
    
    // 获取老师名称
    getTeacherName(value) {
      const teacher = this.teacherList.find(item => item.value === value);
      return teacher ? teacher.label : '';
    },
    // 查看PDF文档
    viewPDF(item) {
      console.log('查看PDF，item数据：', item);
      
      // 调试：检查token和header
      const Cookie = require('js-cookie');
      const token = Cookie.get('token');
      const header = this.$store.state.header;
      console.log('Token:', token);
      console.log('Header名称:', header);
      console.log('taskId:', item.taskId);
      
      if (item.evidence != "[]") {
        this.currentPDFData = item;
        this.pdfError = "";
        this.pdfUrl = []; // 清空之前的URL列表
        
        // 构建PDF查看URL - 需要传递必要的参数
        // 后端使用 @RequestParam，使用 $get 方法传递参数
        this.$get('/api/project/item/selectIntoTaskFile', {
          taskId: item.taskId,
          userId: item.userId
        }).then((res) => {
          console.log('selectIntoTaskFile接口响应：', res);
          
          // 判断接口是否成功
          if (res && res.code == 200) {
            // 检查是否有数据
            if (res.data && Array.isArray(res.data) && res.data.length > 0) {
              // 遍历返回的文件列表，构建完整的PDF URL
              // 使用 /api 前缀，利用 Vue 的代理配置（config/index.js）
              res.data.forEach((filePath) => {
                const fullUrl = "/api" + filePath;
                this.pdfUrl.push(fullUrl);
                console.log('添加PDF URL:', fullUrl);
              });
              
              console.log('所有PDF URLs:', this.pdfUrl);
              
              // 打开弹窗显示第一个PDF
              this.pdfDialogVisible = true;
            } else {
              // 数据为空数组或不存在
              console.log('返回的文件列表为空');
              this.$message.warning('该任务暂无附件可查看');
            }
          } else {
            // 接口返回错误
            console.error('接口返回异常：', res);
            this.$message.error((res && res.msg) || '获取PDF文件列表失败');
          }
        }).catch((error) => {
          // 网络错误或其他异常
          console.error('获取PDF文件列表失败：', error);
          this.$message.error('获取PDF文件列表失败，请检查网络连接');
        });
        
      } else {
        this.$message({
          message: "暂无附件可查看",
          type: "warning",
        });
      }
    },
    
    // 关闭PDF弹窗
    handlePDFDialogClose(done) {
      this.pdfUrl = [];
      this.pdfError = "";
      this.currentPDFData = null;
      done();
    },
    
    // 下载PDF
    downloadPDF() {
      if (this.currentPDFData) {
        this.$downs(
          "/api/evidence/exportToZip",
          {
            projectId: this.currentPDFData.projectId,
            userId: this.currentPDFData.userId,
            evidence: this.currentPDFData.evidence,
          },
          ".zip"
        ).then((res) => {
          this.$message({
            message: "下载成功",
            type: "success",
          });
        });
      }
    },
    DownloadWord(item) {
      console.log(item);
      if (item.evidence != "[]") {
        //   this.$get('/api/evidence/exportToZip',{
        //   evidence:item.evidence
        // })
        // let res=await this.$down('/api/evidence/exportToZip?projectId='+item.projectId+'&userId='+item.userId+'&evidence='+item.evidence,'.zip')
        this.$downs(
          "/api/evidence/exportToWord",
          {
            projectId: item.projectId,
            userId: item.userId,
            evidence: item.evidence,
          },
          ".docx"
        ).then((res) => {});
        this.$message({
          message: "下载成功",
          type: "success",
        });
      } else {
        this.$message({
          message: "暂无附件下载",
          type: "warning",
        });
      }
    },
    Inquire() {
      this.tableData = this.newArr;
      if (this.subtaskSelect == "") {
        this.$message({
          message: "请先选择子任务",
          type: "warning",
        });
      } else {
        this.tableData = [];
        for (var i = 0; i < this.newArr.length; i++) {
          // console.log('score',(this.newArr[i].title == this.projectName.split("-")[0]));
          console.log(this.newArr);
          
          // 构建筛选条件
          let matchProject = !this.projectId || this.newArr[i].projectId == this.projectId;
          let matchCategory = !this.categoryName || this.newArr[i].category == this.categoryName;
          let matchTask = !this.subtaskSelect || this.newArr[i].taskName == this.subtaskSelect;
          let matchScore = !this.RatingValue || this.newArr[i].score > this.RatingValue;
          let matchTeacher = !this.selectedTeacher || this.newArr[i].nickName == this.getTeacherName(this.selectedTeacher);
          
          if (matchProject && matchCategory && matchTask && matchScore && matchTeacher) {
            this.tableData.push(this.newArr[i]);
          }
        }
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    handleSizeChange(val) {
      this.size = val;
    },
    handleCurrentChange(val) {
      this.current = val;
    },
    showMore() {
      if (this.current < this.Total / this.size) {
        this.current++;
      } else {
        this.$message({
          message: "已经是最后一页",
          type: "warning",
        });
      }
    },
    async AllData() {
      await this.$get("/api/project/subTaskScores", {
        projectId: this.projectId || "",
        taskCategory: this.categoryName || "",
        taskName: this.subtaskSelect || "",
        userId: this.selectedTeacher || "",
      }).then((res) => {
        this.tableData = res.data.list;
        this.newArr = res.data.list;
      });
    },
    async tabSelect(item) {
      console.log(this.subtaskSelect);
      if (item == this.projectId) {
        this.categoryName = "";
        this.subtaskSelect = "";
        await this.$get("/api/project/projectCategory/" + this.projectId).then(
          (res) => {
            this.categoryNameData = res.data.data;
          }
        );
        await this.$get("/api//project/selectTeachAllByProjectId",{
          projectId: this.projectId
        }).then((res) => {
          console.log('获取教师列表响应：', res);
          // 检查返回的数据
          if (res && res.code === 200 && res.data) {
            // 后端返回的是对象，需要转换为数组
            if (Array.isArray(res.data)) {
              // 如果是数组格式
              this.teacherList = res.data.map(item => ({
                value: item.userId,
                label: item.nickName
              }));
            } else if (typeof res.data === 'object') {
              // 如果是对象格式（userName作为key）
              this.teacherList = Object.values(res.data).map(item => ({
                value: item.userId,
                label: item.nickName
              }));
              console.log('转换后的教师列表：', this.teacherList);
            } else {
              console.error('教师列表数据格式错误：', res);
              this.teacherList = [];
              this.$message.warning('获取教师列表失败');
            }
          } else {
            console.error('接口返回异常：', res);
            this.teacherList = [];
            this.$message.warning('获取教师列表失败');
          }
        }).catch((error) => {
          console.error('获取教师列表错误：', error);
          this.teacherList = [];
          this.$message.error('获取教师列表失败，请稍后重试');
        });
      } else if (item == this.categoryName) {
        await this.$get("/api/project/subTaskName", {
          pId: this.projectId,
          category: this.categoryName,
        }).then((res) => {
          this.subtask = res.data;
        });
        this.subtaskSelect = "";
      }
      this.AllData();
    },
  },
  computed: {
    ProjectNameData() {
      return this.projectDataArr;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table >>> td > .cell {
  text-align: center;
}

.pdf-viewer-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pdf-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #409eff;
  font-size: 16px;
  
  i {
    font-size: 24px;
    margin-bottom: 10px;
  }
}

.pdf-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #f56c6c;
  font-size: 16px;
  
  i {
    font-size: 24px;
    margin-bottom: 10px;
  }
}

.pdf-content {
  width: 100%;
  height: 100%;
  
  iframe {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
  }
}

.pdf-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: #909399;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}
</style>